package com.example.demo.advice;

import com.example.demo.exception.BusinessException;
import com.example.demo.exception.ThrowableException;
import com.example.demo.pojo.ResultPojo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @Description:
 * @Auther:ccc
 * @Date:2022/11/12 20:17
 */
@Slf4j
@ControllerAdvice
public class MyAdvice {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultPojo dealDefaultException(Exception exception) {
        log.error("default", exception);
        return new ResultPojo("default", exception.getMessage());
    }

    /**
     * 处理抛出的业务异常
     *
     * @param businessException
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResultPojo dealAdvice(BusinessException businessException) throws ThrowableException {
        String errCode = businessException.getErrCode();
        String message = businessException.getErrMsg();
        if ("code001".equals(errCode)) {
            throw new ThrowableException("002", "secondException", businessException);
        }
        return new ResultPojo(errCode, message);
    }

    /**
     * 处理抛出的参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultPojo dealValidation(MethodArgumentNotValidException e) {
        e.printStackTrace();
        String defaultMessage = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        String errCode = "1324";
        return new ResultPojo(errCode, defaultMessage);
    }

    /**
     * 处理抛出的方法执行异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ThrowableException.class)
    @ResponseBody
    public ResultPojo dealMethodError(ThrowableException e) {
        String errCode = e.getErrCode();
        String errMsg = e.getErrMsg();
        log.error(errCode.concat(errMsg));
        log.error(errCode, e.getThrowable());
        return new ResultPojo(errCode, errMsg);
    }

}
